import { menu } from '../../../app/decorator';
import ShapPolygon from '../shap/ShapPolygon';
import BaseColorShap from './base/BaseColorShap';

const { ccclass, disallowMultiple, executeInEditMode, requireComponent } = cc._decorator;

@ccclass
@menu(__filename, '多边形')
@disallowMultiple()
@executeInEditMode()
@requireComponent(ShapPolygon)
export default class ColorShapPolygon extends BaseColorShap {

    constructor() {
        super();

        this._needLineJoin = true;
    }

    onLoad() {
        super.onLoad();

        this.node.on('offset-change', this.handle, this);
        this.node.on('points-change', this.handle, this);
    }

    private handle() {
        if (CC_EDITOR) {
            const polygon = this.getComponent(ShapPolygon);
            const points = polygon.points;

            if (points.length === 1 || points.length === 0) {
                this._canStroke = false;
                this._canFill = true;

                this._needLineJoin = false;
                this._needLineCap = false;
                this._needMiterLimit = false;
            } else if (points.length === 2) {
                this._canStroke = true;
                this._canFill = false;

                this._needLineJoin = false;
                this._needLineCap = true;
                this._needMiterLimit = true;
            } else {
                this._canStroke = true;
                this._canFill = true;

                this._needLineJoin = true;
                this._needLineCap = false;
                this._needMiterLimit = true;
            }
        }
        this.updateColorShap();
    }

    onDraw(cxt: cc.Graphics) {
        const polygon = this.getComponent(ShapPolygon);

        const points = polygon.points;

        if (points.length === 0) { 0; }
        else if (points.length === 1) {
            cxt.circle(points[0].x + polygon.offset.x, points[0].y + polygon.offset.y, 1);
        } else if (points.length === 2) {
            cxt.moveTo(points[0].x + polygon.offset.x, points[0].y + polygon.offset.y);
            cxt.lineTo(points[1].x + polygon.offset.x, points[1].y + polygon.offset.y);
        } else {
            cxt.moveTo(points[0].x + polygon.offset.x, points[0].y + polygon.offset.y);
            for (let index = 1; index < points.length; index++) {
                cxt.lineTo(points[index].x + polygon.offset.x, points[index].y + polygon.offset.y);
            }
            cxt.close();
        }
    }
}
